
const data = [
  { id: 1, parentId: null, name: 'Node 1' },
  { id: 2, parentId: 1, name: 'Node 1.1' },
  { id: 3, parentId: 1, name: 'Node 1.2' },
  { id: 4, parentId: 3, name: 'Node 1.2.1' },
  { id: 5, parentId: 3, name: 'Node 1.2.2' },
  { id: 6, parentId: null, name: 'Node 2' },
  { id: 7, parentId: 6, name: 'Node 2.1' },
  { id: 8, parentId: 6, name: 'Node 2.2' },
]

var data2 = [
  { id: 1, name: "办公管理", parentId: 0 },
  { id: 2, name: "请假申请", parentId: 1 },
  { id: 3, name: "出差申请", parentId: 1 },
  { id: 4, name: "请假记录", parentId: 2 },
  { id: 5, name: "系统设置", parentId: 0 },
  { id: 6, name: "权限管理", parentId: 5 },
  { id: 7, name: "用户角色", parentId: 6 },
  { id: 8, name: "菜单设置", parentId: 6 },
]

function buildTree (data, parentId) {
  const tree = []
  data.map(item => {
    if (item.parentId === parentId) {
      const children = buildTree(data, item.id)
      if (children.length > 0) {
        item.children = children
      }
      tree.push(item)
    }
  })
  return tree
}
// console.log(buildTree(data, null))


function toTree (data) {
  let maps = {};
  let list = [];
  data.forEach(function (item) {
    let { id, parentId } = item
    maps[id] = { ...item }
    let parent = maps[parentId];
    if (parent) {
      (parent.children || (parent.children = [])).push(maps[id]);
    } else {
      list.push(maps[id]);
    }
    // 下面这个可以省略
    // delete maps[id].children
  });
  return list;
}

console.log(toTree(data))